﻿using Coldairarrow.Business.Aps;
using Coldairarrow.Entity.Aps;
using Coldairarrow.Util;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.Aps
{
    /// <summary>
    /// 应用密钥
    /// </summary>
    /// <seealso cref="Coldairarrow.Api.BaseApiController" />
    [Route("/Aps/[controller]/[action]")]
    public class Aps_ProductMaterialController : BaseApiController
    {
        #region DI

        public Aps_ProductMaterialController(IAps_ProductMaterialBusiness dbLinkBus, IAps_ProductProcessBusiness dbLinkBus2)
        {
            _dbLinkBus = dbLinkBus;
            _dbLinkBus2 = dbLinkBus2;
        }

        IAps_ProductMaterialBusiness _dbLinkBus { get; }
        IAps_ProductProcessBusiness _dbLinkBus2 { get; }
        #endregion

        #region 获取

        [HttpPost]
        public async Task<AjaxResult<List<Aps_ProductMaterial>>> GetDataList(PageInput<Aps_ProductMaterial> input)
        {
            return await _dbLinkBus.GetDataListAsync(input);
        }

        [HttpPost]
        public async Task<Aps_ProductMaterial> GetTheData(IdInputDTO input)
        {
            return await _dbLinkBus.GetTheDataAsync(input.id) ?? new Aps_ProductMaterial();
        }

        #endregion

        #region 提交

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="theData">保存的数据</param>
        [HttpPost]
        public async Task SaveData(Models.ProductBom theData)
        {
            if (theData.ProductMaterialList != null)
            {
                foreach(var model in theData.ProductMaterialList)
                {
                    if (string.IsNullOrEmpty(model.Id))
                    {
                        InitEntity(model);

                        await _dbLinkBus.AddDataAsync(model);
                    }
                    else
                    {
                        await _dbLinkBus.UpdateDataAsync(model);
                    }
                }
            }
            if (theData.ProductProcessList!=null)
            {
                foreach (var model in theData.ProductProcessList)
                {
                    if (string.IsNullOrEmpty(model.Id))
                    {
                        InitEntity(model);

                        await _dbLinkBus2.AddDataAsync(model);
                    }
                    else
                    {
                        await _dbLinkBus2.UpdateDataAsync(model);
                    }
                }
            }
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="ids">id数组,JSON数组</param>
        [HttpPost]
        public async Task DeleteData(List<string> ids)
        {
            await _dbLinkBus.DeleteDataAsync(ids);
        }

        #endregion
    }
}